package com.jiubanqingchen.future.common.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Record;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class SystemTool {

    private static Logger logger = LoggerFactory.getLogger(SystemTool.class);

    private static final String[] HEADERS = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
             "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR",
            "X-Real-IP"
    };

    /**
     * 判断ip是否为空，空返回true
     *
     * @param ip
     * @return
     */
    public static boolean isEmptyIp(final String ip) {
        return (ip == null || ip.length() == 0 || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip));
    }


    /**
     * 判断ip是否不为空，不为空返回true
     *
     * @param ip
     * @return
     */
    public static boolean isNotEmptyIp(final String ip) {
        return !isEmptyIp(ip);
    }

    /***
     * 获取客户端ip地址(可以穿透代理)
     * @param request HttpServletRequest
     * @return
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String ip = "";
        for (String header : HEADERS) {
            ip = request.getHeader(header);
            if (isNotEmptyIp(ip)) {
                break;
            }
        }
        if (isEmptyIp(ip)) {
            ip = request.getRemoteAddr();
        }
        if (isNotEmptyIp(ip) && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }


    /**
     * 得到客户端ip地址区域信息
     *
     * @param ip
     * @return
     */
    public static String getClientIpArea(String ip) throws Exception {
        Prop p = PropKit.use("map.properties");
        String key = p.get("key");
        String url = "https://restapi.amap.com/v3/ip?ip=" + ip + "&key=" + key;
        String jsonString = HttpKit.get(url);
        JSONObject json = JSON.parseObject(jsonString);
        if ("1".equals(json.getString("status"))) {//高德 status 1:成功 0 失败
            return json.getString("province") + " " + json.getString("city");
        } else {
            throw new Exception(json.get("info").toString());
        }
    }

    /**
     * 获取请求UserAgent
     *
     * @param request
     * @return
     */
    public static UserAgent getUserAgent(HttpServletRequest request) {
        //获取浏览器信息
        String ua = request.getHeader("User-Agent");
        //转成UserAgent对象
        return UserAgent.parseUserAgentString(ua);
    }

    /**
     * 得到ip信息
     *
     * @param request
     * @return
     */
    public static Record getIpInfo(HttpServletRequest request) {
        //获取用户ip地址
        String ip= getClientIpAddress(request);
        Record record = new Record().set("ipAddress", ip);
        if (!"127.0.0.1".equals(ip)) { //获取ip信息
            try {
                record.set("ipArea", getClientIpArea(ip));
            }catch (Exception e){
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        } else {
            record.set("ipArea", "局域网");
        }
        return record;
    }
}